/*
Copyright (C) 1996-1997 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include "quakedef.h"

void CL_FinishTimeDemo (void);

/*
==============================================================================

DEMO CODE

When a demo is playing back, all NET_SendMessages are skipped, and
NET_GetMessages are read from the demo file.

Whenever cl.time gets past the last received message, another message is
read from the demo file.
==============================================================================
*/

// JPG 1.05 - support for recording demos after connecting to the server
byte	demo_head[3][MAX_MSGLEN];
int		demo_head_size[2];


/*
==============
CL_StopPlayback

Called when a demo file runs out, or the user starts a game
==============
*/
void CL_StopPlayback (void)
{
	if (!cls.demoplayback)
		return;

	fclose (cls.demofile);
	cls.demoplayback = FALSE;
	cls.demofile = NULL;
	cls.state = ca_disconnected;

	if (cls.timedemo)
		CL_FinishTimeDemo ();
}

/* JPG - need to fix up the demo message
==============
CL_FixMsg
==============
*/
void CL_FixMsg (int fix)
{
	char *s1 = "coop 0";
	char *s2 = "cmd xs";
	int match = 0;
	char *s = fix ? s1 : s2;

	MSG_BeginReading ();

	while (1)
	{
		if (msg_badread) return;
		if (MSG_ReadByte () != svc_stufftext) return;

		while (1)
		{
			int c = MSG_ReadChar ();

			if (c == -1 || c == 0)
				break;
			else if (c == s[match])
			{
				match++;

				if (match == 6)
				{
					for (int i = 0; i < 6; i++)
						net_message.data[msg_readcount - 6 + i] ^= s1[i] ^ s2[i];

					match = 0;
				}
			}
			else match = 0;
		}
	}
}


/*
====================
CL_WriteDemoMessage

Dumps the current net message, prefixed by the length and view angles
====================
*/
void CL_WriteDemoMessage (void)
{
	int		len;
	int		i;
	float	f;

	len = LittleLong (net_message.cursize);
	fwrite (&len, 4, 1, cls.demofile);

	for (i = 0; i < 3; i++)
	{
		f = LittleFloat (cl.viewangles[i]);
		fwrite (&f, 4, 1, cls.demofile);
	}

	CL_FixMsg (1); // JPG - some demo things are bad
	fwrite (net_message.data, net_message.cursize, 1, cls.demofile);
	CL_FixMsg (0); // JPG - some demo things are bad

	fflush (cls.demofile);
}

/*
====================
CL_GetMessage

Handles recording and playback of demos, on top of NET_ code
====================
*/
int CL_GetMessage (void)
{
	int		r, i;
	float	f;

	if	(cls.demoplayback)
	{
		// decide if it is time to grab the next message
		if (cls.signon == SIGNONS)	// allways grab until fully connected
		{
			if (cls.timedemo)
			{
				if (host_framecount == cls.td_lastframe)
					return 0;		// allready read this frame's message

				cls.td_lastframe = host_framecount;

				// if this is the second frame, grab the real td_starttime
				// so the bogus time on the first frame doesn't count
				if (host_framecount == cls.td_startframe + 1)
					cls.td_starttime = realtime;
			}
			else if (/* cl.time > 0 && */ cl.time <= cl.mtime[0])
			{
				return 0;		// don't need another message yet
			}
		}

		// get the next message
		fread (&net_message.cursize, 4, 1, cls.demofile);
		VectorCopy (cl.mviewangles[0], cl.mviewangles[1]);

		for (i = 0; i < 3; i++)
		{
			r = fread (&f, 4, 1, cls.demofile);
			cl.mviewangles[0][i] = LittleFloat (f);
		}

		net_message.cursize = LittleLong (net_message.cursize);

		if (net_message.cursize > MAX_MSGLEN)
			Sys_Error ("Demo message > MAX_MSGLEN");

		r = fread (net_message.data, net_message.cursize, 1, cls.demofile);

		if (r != 1)
		{
			CL_StopPlayback ();
			return 0;
		}

		return 1;
	}

	while (1)
	{
		r = NET_GetMessage (cls.netcon);

		if (r != 1 && r != 2)
			return r;

		// discard nop keepalive message
		if (net_message.cursize == 1 && net_message.data[0] == svc_nop)
			Con_Printf (PRINT_SAFE, "<-- server to client keepalive\n");
		else
			break;
	}

	if (cls.demorecording)
		CL_WriteDemoMessage ();

	// JPG 1.05 - support for recording demos after connecting
	if (cls.signon < 2)
	{
		memcpy (demo_head[cls.signon], net_message.data, net_message.cursize);
		demo_head_size[cls.signon] = net_message.cursize;
	}

	return r;
}


/*
====================
CL_Stop_f

stop recording a demo
====================
*/
void CL_Stop_f (void)
{
	if (cmd_source != src_command)
		return;

	if (!cls.demorecording)
	{
		Con_Printf (PRINT_SAFE, "Not recording a demo.\n");
		return;
	}

	// write a disconnect message to the demo file
	SZ_Clear (&net_message);
	MSG_WriteByte (&net_message, svc_disconnect);
	CL_WriteDemoMessage ();

	// finish up
	fclose (cls.demofile);
	cls.demofile = NULL;
	cls.demorecording = FALSE;
	Con_Printf (PRINT_SAFE, "Completed demo\n");

	// reset the autocomplete list to include the new demo
	// (this really just should add the new item but enumeration is fast enough so oh well)
	FS_EnumerateDemos ();
}


void CL_UpdateDemoStat (int stat)
{
	if (stat < 0 || stat >= MAX_CL_STATS) return;

	MSG_WriteByte (&net_message, svc_updatestat);
	MSG_WriteByte (&net_message, stat);
	MSG_WriteLong (&net_message, cl.stats[stat]);
}

/*
====================
CL_Record_f

record <demoname> <map> [cd track]
====================
*/
void CL_Record_f (void)
{
	int		c;
	char	name[MAX_OSPATH];
	int		track;

	if (cmd_source != src_command)
		return;

	c = Cmd_Argc ();

	if (c != 2 && c != 3 && c != 4)
	{
		Con_Printf (PRINT_SAFE, "record <demoname> [<map> [cd track]]\n");
		return;
	}

	if (strstr (Cmd_Argv (1), ".."))
	{
		Con_Printf (PRINT_SAFE, "Relative pathnames are not allowed.\n");
		return;
	}

	// JPG 3.00 - consecutive demo bug
	if (cls.demorecording)
		CL_Stop_f ();

	/* JPG 1.05 - got rid of this because recording after connecting is now supported
	if (c == 2 && cls.state == ca_connected)
	{
		Con_Printf (PRINT_SAFE, "Can not record - already connected to server\nClient demo recording must be started before connecting\n");
		return;
	}
	*/

	// JPG 1.05 - replaced it with this
	if (c == 2 && cls.state == ca_connected && cls.signon < 2)
	{
		Con_Printf (PRINT_SAFE, "Can't record - try again when connected\n");
		return;
	}

	// write the forced cd track number, or -1
	if (c == 4)
	{
		track = atoi (Cmd_Argv (3));
		Con_Printf (PRINT_SAFE, "Forcing CD track to %i\n", cls.forcetrack);
	}
	else track = -1;

	sprintf (name, "%s/%s", com_gamedir, Cmd_Argv (1));

	// start the map up
	if (c > 2)
		Cmd_ExecuteString (va ("map %s", Cmd_Argv (2)), src_command);

	// open the demo file
	FS_DefaultExtension (name, ".dem");

	Con_Printf (PRINT_SAFE, "recording to %s.\n", name);
	cls.demofile = fopen (name, "wb");

	if (!cls.demofile)
	{
		Con_Printf (PRINT_SAFE, "ERROR: couldn't open.\n");
		return;
	}

	cls.forcetrack = track;
	fprintf (cls.demofile, "%i\n", cls.forcetrack);

	cls.demorecording = TRUE;

	// JPG 1.05 - initialize the demo file if we're already connected
	if (c == 2 && cls.state == ca_connected)
	{
		byte *data = net_message.data;
		int cursize = net_message.cursize;

		for (int i = 0; i < 2; i++)
		{
			net_message.data = demo_head[i];
			net_message.cursize = demo_head_size[i];
			CL_WriteDemoMessage();
		}

		net_message.data = demo_head[2];
		SZ_Clear (&net_message);
		
		// current names, colors, and frag counts
		for (int i = 0; i < cl.maxclients; i++)
		{
			MSG_WriteByte (&net_message, svc_updatename);
			MSG_WriteByte (&net_message, i);
			MSG_WriteString (&net_message, cl.scores[i].name);

			MSG_WriteByte (&net_message, svc_updatefrags);
			MSG_WriteByte (&net_message, i);
			MSG_WriteShort (&net_message, cl.scores[i].frags);

			MSG_WriteByte (&net_message, svc_updatecolors);
			MSG_WriteByte (&net_message, i);
			MSG_WriteByte (&net_message, cl.scores[i].colors);
		}
		
		// send all current light styles
		for (int i = 0; i < MAX_LIGHTSTYLES; i++)
		{
			MSG_WriteByte (&net_message, svc_lightstyle);
			MSG_WriteByte (&net_message, i);
			MSG_WriteString (&net_message, cl_lightstyle[i].map);
		}

		// update stats for single player
		CL_UpdateDemoStat (STAT_TOTALSECRETS);
		CL_UpdateDemoStat (STAT_TOTALMONSTERS);
		CL_UpdateDemoStat (STAT_SECRETS);
		CL_UpdateDemoStat (STAT_MONSTERS);

		// view entity
		MSG_WriteByte (&net_message, svc_setview);
		MSG_WriteShort (&net_message, cl.viewentity);
		
		// signon
		MSG_WriteByte (&net_message, svc_signonnum);
		MSG_WriteByte (&net_message, 3);
		
		CL_WriteDemoMessage ();
		
		// restore net_message
		net_message.data = data;
		net_message.cursize = cursize;
	}

	// remove the console
	Key_SetDest (key_game);
}


/*
====================
CL_PlayDemo_f

play [demoname]
====================
*/
void CL_PlayDemo_f (void)
{
	char name[256];
	int c;
	BOOL neg = FALSE;

	if (cmd_source != src_command)
		return;

	if (Cmd_Argc () != 2)
	{
		Con_Printf (PRINT_SAFE, "play <demoname> : plays a demo\n");
		return;
	}

	// disconnect from server
	CL_Disconnect ();

	// open the demo file
	strcpy (name, Cmd_Argv (1));
	FS_DefaultExtension (name, ".dem");

	Con_Printf (PRINT_SAFE, "Playing demo from %s.\n", name);
	FS_FOpenFile (name, &cls.demofile);

	if (!cls.demofile)
	{
		Con_Printf (PRINT_SAFE, "ERROR: couldn't open.\n");
		cls.demonum = -1;		// stop demo loop
		return;
	}

	cls.demoplayback = TRUE;
	cls.state = ca_connected;
	cls.forcetrack = 0;

	while ((c = getc (cls.demofile)) != '\n')
	{
		if (c == '-')
			neg = TRUE;
		else cls.forcetrack = cls.forcetrack * 10 + (c - '0');
	}

	if (neg)
		cls.forcetrack = -cls.forcetrack;

	// ZOID, fscanf is evil
	//	fscanf (cls.demofile, "%i\n", &cls.forcetrack);
}

/*
====================
CL_FinishTimeDemo

====================
*/
void CL_FinishTimeDemo (void)
{
	cls.timedemo = FALSE;

	if (d3d_SwapChain)
	{
		UINT pcount = 0;

		if (SUCCEEDED (d3d_SwapChain->GetLastPresentCount (&pcount)))
		{
			// the first frame didn't count
			int frames = (pcount - cls.td_startPresent) - 1;
			float time = realtime - cls.td_starttime;

			if (!time)
				time = 1;

			float fps = frames / time;

			Con_Printf (PRINT_SAFE, "%i frames %5.1f seconds %5.1f fps\n", frames, time, fps);
		}
	}
}

/*
====================
CL_TimeDemo_f

timedemo [demoname]
====================
*/
void CL_TimeDemo_f (void)
{
	if (!d3d_SwapChain) return;
	if (cmd_source != src_command) return;

	if (Cmd_Argc () != 2)
	{
		Con_Printf (PRINT_SAFE, "timedemo <demoname> : gets demo speeds\n");
		return;
	}

	CL_PlayDemo_f ();

	// cls.td_starttime will be grabbed at the second frame of the demo, so
	// all the loading time doesn't get counted

	// only go into timedemo mode if a demo was successfully opened
	if (cls.demofile)
	{
		// measure timedemo by actual presents
		d3d_SwapChain->GetLastPresentCount (&cls.td_startPresent);

		cls.timedemo = TRUE;
		cls.td_startframe = host_framecount;
		cls.td_lastframe = -1;		// get a new message this frame
	}
}

